package com.ibeetl.eval;

import java.lang.reflect.Method;

import org.beetl.core.Context;
import org.beetl.core.exception.BeetlException;
import org.beetl.core.om.ObjectAA;
import org.beetl.core.statement.VarRef;

public class ExcelVarRef extends VarRef {
	String attr;
	public ExcelVarRef(VarRef ref) {
		super(ref.attributes, ref.hasSafe, ref.safe, ref.token, ref.token);
		this.varIndex = ref.varIndex;
		attr = getAttrNameIfRoot(ref.token.text);

	}
	@Override
	public Object evaluate(Context ctx) {

		Object value = ctx.vars[varIndex];
		if (value == Context.NOT_EXIST_OBJECT) {
			// check root
			TreeNode node  = (TreeNode) ctx.getGlobal("_root");
			TreeNode root = getRootNode(node);
			TreeNode varNode = root.findTreeNodeByName(this.attr);
			if(varNode==null){
				return super.evaluate(ctx);
			}else{
				Object val = varNode.getResult();
				return val;
			}
		}
		return super.evaluate(ctx);
	}
	
	private TreeNode getRootNode(TreeNode node){
		TreeNode temp = null;
		while(node.getParentNode()!=null){
			temp = node.getParentNode();;
			node = temp;
		}
		return temp;
	}
	private String getAttrNameIfRoot(String name){
		//todo []
		int index = name.indexOf('.');
		if(index!=-1){
			return name.substring(0, index);
		}else{
			return name;
		}
	}
}
